<?php
declare (strict_types = 1);

namespace app\adminapi\controller;

use app\adminapi\extend\tools\jwt\Token;
use think\exception\ValidateException;
use think\facade\Log;
use think\Request;
use app\BaseController;
use think\captcha\facade\Captcha;
class Login extends BaseController
{
    /**
     * 显示同个域名下的登录界面
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        return view('login');
    }

    /**
     * 验证接到的数据并且传递token
     * @param Request $request
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function check(Request $request)
    {
        //
        $data=$request->all();
        try {

            //验证字段是否非空
            validate(\app\adminapi\validate\Login::class)->check($data);//token和验证码是自己生成的，所以验证器不能用token和captcha了,需要创建专门的中间件验证
            //查询数据
            $obj=new \app\common\model\Login();
            $res= $obj->where('username',$data['username'])->find();
            if($res){
                if($res['password']==md5($data['password'])){
                    //session('username',$data['username']);这步不要了，用token
                    //获取用户id，生成token
                    $token= ['token' => Token::getToken($res['id'])];//这步非常重要！！！

                    Log::write($data['username'].'登陆成功','info');
                    return jsons('200','登录成功',$token);
                }else{
                    return fail('密码错误');
                }
            }else{
                return  fail('账号错误');
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return fail($e->getError());
        }
    }

    /**
     * 生成验证码的路径
     * @return \think\response\Json
     */
    public function getCaptcha(){
        $uniqid = uniqid((string)mt_rand(100000, 999999));
        //返回数据 验证码图片路径、验证码标识
        Captcha::create();
        $data = [
            'src' => 'http://adminapi.pyg.com'.captcha_src(),
            'uniqid' => $uniqid
        ];

        return jsons('200','ok',$data);
    }



    public function test(){
        $token = Token::getToken(200);
        dump($token);
//解析token 得到用户id
        $user_id =Token::getUserId($token);
        dd($user_id);
    }

    /**
     * 退出登录
     * @return \think\response\Json
     * @throws \Exception
     */
    public function logout()
    {
        //清空token  将需清空的token存入缓存，再次使用时，会读取缓存进行判断
        $token = Token::getRequestToken();
        $delete_token = cache('delete_token') ?: [];
        $delete_token[] = $token;
        $res=cache('delete_token', $delete_token, 86400);
        return successes('成功');
    }

    public function show(){
      return view('index');
    }

}
